package week5.day30;


/**
 * @Author fengzihao
 * @Date 2024-05-14 19:37
 */
public class CheckNodeCircle {
    public static void main(String[] args) {
        // a --> b --> c --> d --> e
        Node e = new Node("e");
        Node d = new Node("d", e);
        Node c = new Node("c", d);
        Node b = new Node("b", c);
        Node a = new Node("a", b);

        // a --> b --> c --> d --> e --> c --> d --> e --> ...
        e.next = c;

        boolean bool = hasCircle(a);
        System.out.println(bool);
    }
    /**
     * 判断链表是否有环
     * @param head : 头结点
     * @return : 是否有环
     */
    private static boolean hasCircle(Node head) {
        Node fastNode = head;
        Node lowNode = head;
        while(fastNode.next!=null&&lowNode.next!=null){
            fastNode=fastNode.next;
            fastNode = fastNode.next;
            lowNode = lowNode.next;
            if (fastNode==lowNode)
                return true;
        }
        return false;
    }
}
class Node{
    String data;
    Node next;

    public Node() {
    }

    public Node(String data) {
        this.data = data;
    }

    public Node(String data, Node next) {
        this.data = data;
        this.next = next;
    }

    @Override
    public String toString() {
        return "Node{" +
                "data='" + data + '\'' +
                ", next=" + next +
                '}';
    }
}
